
# 格式化json
function formatJson() {
    # python -m json.tool
    python -c "import json,sys;sys.stdout.write(json.dumps(json.load(sys.stdin), sort_keys=True, indent=4));sys.stdout.write('\n');"
}
# json='{"a": 1, "b": {"c": "zhouqian"}}'
# echo "$json" | formatJson
# echo "$json" | getJsonValueByPython "a"
# echo "结果为 $?"


# 使用Python解析json
function getJsonValueByPython() {
    if which python; then
        local key="$1"
        python -c "import json,sys; sys.stdout.write(json.dumps(json.load(sys.stdin).get('$key')));sys.stdout.write('\n');"
        return 0
    else
        return 1
    fi
}
# json2='{"a": 1, "b": {"ca": "zhouqian"}, "zq": 100, "zq": "101"}'
# getJsonValuesByAwk "$json" "a" "defaultValue"
# getJsonValuesByAwk "$json" "b" "defaultValue"
# getJsonValuesByAwk "$json" "ca" "defaultValue"
# getJsonValuesByAwk "$json" "zhouqian" "defaultValue"   // print defaultValue
# getJsonValuesByAwk "$json" "zq" "defaultValue"     // print 100 "101" in two lines


# Linux原生解析json
function getJsonValuesByAwk() {
    awk -v json="$1" -v key="$2" -v defaultValue="$3" 'BEGIN{
        foundKeyCount = 0
        while (length(json) > 0) {
            # pos = index(json, "\""key"\""); ## 这行更快一些，但是如果有value是字符串，且刚好与要查找的key相同，会被误认为是key而导致值获取错误
            pos = match(json, "\""key"\"[ \\t]*?:[ \\t]*");
            if (pos == 0) {if (foundKeyCount == 0) {print defaultValue;} exit 0;}

            ++foundKeyCount;
            start = 0; stop = 0; layer = 0;
            for (i = pos + length(key) + 1; i <= length(json); ++i) {
                lastChar = substr(json, i - 1, 1)
                currChar = substr(json, i, 1)

                if (start <= 0) {
                    if (lastChar == ":") {
                        start = currChar == " " ? i + 1: i;
                        if (currChar == "{" || currChar == "[") {
                            layer = 1;
                        }
                    }
                } else {
                    if (currChar == "{" || currChar == "[") {
                        ++layer;
                    }
                    if (currChar == "}" || currChar == "]") {
                        --layer;
                    }
                    if ((currChar == "," || currChar == "}" || currChar == "]") && layer <= 0) {
                        stop = currChar == "," ? i : i + 1 + layer;
                        break;
                    }
                }
            }

            if (start <= 0 || stop <= 0 || start > length(json) || stop > length(json) || start >= stop) {
                if (foundKeyCount == 0) {print defaultValue;} exit 0;
            } else {
                print substr(json, start, stop - start);
            }

            json = substr(json, stop + 1, length(json) - stop)
        }
    }'
}
# msgdata='{"a": 1, "b": {"ca": "zhouqian"}, "zq": 100, "zq": "101"}'
# echo $msgdata
# getJsonValuesByAwk $msgdata "zq"
# getJsonValuesByAwk $msgdata "ca"